import asyncio
from contextlib import asynccontextmanager

from fastapi import Depends
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
    create_engine
)

from .GlobalConfig import config



class SqlalchemyX:
    # 基础类
    Base = declarative_base()

    engine = create_engine(
        config.DATABASE_URL,
        # 超过链接池大小外最多创建的链接
        max_overflow=5,
        # 链接池大小
        pool_size=5,
        # 链接池中没有可用链接则最多等待的秒数，超过该秒数后报错
        pool_timeout=10,
        # 多久之后对链接池中的链接进行一次回收
        pool_recycle=1,
        # 查看原生语句（未格式化）
        echo=True
    )

    db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
    Base.query = db_session.query_property()

    # 创建异步引擎和会话工厂
    engine = create_async_engine(config.ASYNC_DATABASE_URL, echo=True)
    _AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    @staticmethod
    def AsyncSessionLocal():
        session =  SqlalchemyX._AsyncSessionLocal()
        try:
            return session
        except Exception as e:
            raise e
        else:
            asyncio.run_coroutine_threadsafe(session.commit(), asyncio.get_event_loop())
        finally:
            asyncio.run_coroutine_threadsafe(session.close(), asyncio.get_event_loop())

    @staticmethod
    def get_db():
        db = SqlalchemyX.db_session()
        try:
            yield db
        finally:
            db.close()





if __name__ == "__main__":
    import os
    HOST: str = 'ser.loserbai.cn:40036'
    DATABASE = 'demo-im'
    DRIVER: str = ''
    cmd = f"sqlacodegen mysql+pymysql://demo-im:demo-im@{HOST}/{DATABASE} > modules/mod.py"
    print(cmd)
    os.system(cmd)